package com.example.project.service.impl;

import com.example.project.entity.Image;
import com.example.project.mapper.ImageMapper;
import com.example.project.service.ImageService;
import com.example.project.util.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.time.LocalDateTime;
import java.util.UUID;

import javax.servlet.http.HttpServletResponse;

@Service
@Slf4j
public class ImageServiceImpl implements ImageService {
    
    @Autowired
    private ImageMapper imageMapper;
    
    @Value("${file.upload.path}")
    private String uploadPath;

    @PostConstruct
    public void init() {
        // 创建上传目录
        try {
            File uploadDir = new File(uploadPath);
            if (!uploadDir.exists()) {
                uploadDir.mkdirs();
            }
            log.info("文件上传目录: {}", uploadDir.getAbsolutePath());
        } catch (Exception e) {
            log.error("创建上传目录失败", e);
            throw new RuntimeException("Could not create upload directory!");
        }
    }

    @Override
    public Result<?> upload(MultipartFile file, Long userId) {
        try {
            // 生成文件存储路径
            String fileName = generateFileName(file.getOriginalFilename());
            String datePath = generateDatePath();
            String fullPath = uploadPath + datePath;
            
            // 确保目录存在
            File directory = new File(fullPath);
            if (!directory.exists()) {
                directory.mkdirs();
            }
            
            // 完整的文件路径
            File dest = new File(directory, fileName);
            log.info("保存文件到: {}", dest.getAbsolutePath());
            
            // 保存文件
            file.transferTo(dest);
            
            // 保存记录到数据库
            Image image = new Image();
            image.setFileName(fileName);
            image.setFilePath(datePath + "/" + fileName);
            image.setFileSize(file.getSize());
            image.setFileType(file.getContentType());
            image.setImageType(1);
            image.setUserId(userId);
            image.setStatus(1);
            
            imageMapper.insert(image);
            
            return Result.success(image);
        } catch (IOException e) {
            log.error("文件上传失败", e);
            return Result.error("文件上传失败：" + e.getMessage());
        }
    }
    
    @Override
    public Result<?> update(Long imageId, MultipartFile file, Long userId) {
        // 查询原图片记录
        Image oldImage = imageMapper.selectById(imageId);
        if (oldImage == null) {
            return Result.error("图片不存在");
        }
        
        // 验证权限
        if (!oldImage.getUserId().equals(userId)) {
            return Result.error("无权限修改此图片");
        }
        
        try {
            // 生成新文件名和路径
            String fileName = generateFileName(file.getOriginalFilename());
            String datePath = generateDatePath();
            String fullPath = uploadPath + datePath;
            
            // 确保目录存在
            File directory = new File(fullPath);
            if (!directory.exists()) {
                directory.mkdirs();
            }
            
            // 保存新文件
            File dest = new File(directory, fileName);
            log.info("保存新文件到: {}", dest.getAbsolutePath());
            file.transferTo(dest);
            
            // 删除旧文件
            File oldFile = new File(uploadPath + oldImage.getFilePath());
            if (oldFile.exists()) {
                oldFile.delete();
            }
            
            // 更新数据库记录
            oldImage.setFileName(fileName);
            oldImage.setFilePath(datePath + "/" + fileName);
            oldImage.setFileSize(file.getSize());
            oldImage.setFileType(file.getContentType());
            
            imageMapper.updateById(oldImage);
            
            return Result.success(oldImage);
        } catch (IOException e) {
            log.error("图片更新失败", e);
            return Result.error("图片更新失败：" + e.getMessage());
        }
    }
    
    @Override
    public Result<?> delete(Long imageId, Long userId) {
        // 查询图片记录
        Image image = imageMapper.selectById(imageId);
        if (image == null) {
            return Result.error("图片不存在");
        }
        
        // 验证权限
        if (!image.getUserId().equals(userId)) {
            return Result.error("无权限删除此图片");
        }
        
        // 删除文件
        File file = new File(uploadPath + image.getFilePath());
        if (file.exists()) {
            file.delete();
        }
        
        // 删除数据库记录
        imageMapper.deleteById(imageId);
        
        return Result.success(null);
    }
    
    private String generateFileName(String originalFilename) {
        String ext = originalFilename.substring(originalFilename.lastIndexOf("."));
        return UUID.randomUUID().toString().replace("-", "") + ext;
    }
    
    private String generateDatePath() {
        LocalDateTime now = LocalDateTime.now();
        return String.format("/%d/%02d/%02d",
            now.getYear(), now.getMonthValue(), now.getDayOfMonth());
    }

    @Override
    public void getImage(Long imageId, HttpServletResponse response) {
        Image image = imageMapper.selectById(imageId);
        if (image == null) {
            throw new RuntimeException("图片不存在");
        }

        File file = new File(uploadPath + image.getFilePath());
        if (!file.exists()) {
            throw new RuntimeException("图片文件不存在");
        }

        // 设置响应头
        response.setContentType(image.getFileType());
        response.setHeader("Cache-Control", "max-age=2592000"); // 30天缓存

        // 输出图片流
        try (FileInputStream fis = new FileInputStream(file);
             OutputStream os = response.getOutputStream()) {
            byte[] buffer = new byte[1024];
            int len;
            while ((len = fis.read(buffer)) != -1) {
                os.write(buffer, 0, len);
            }
            os.flush();
        } catch (IOException e) {
            log.error("读取图片失败", e);
            throw new RuntimeException("读取图片失败");
        }
    }

    @Override
    public Result<?> getImageInfo(Long imageId) {
        Image image = imageMapper.selectById(imageId);
        if (image == null) {
            return Result.error("图片不存在");
        }
        return Result.success(image);
    }
} 